<?

	final class Interface_Nicename0v0r00 extends _smuoiAppInterface{
		
		/* codes:
			0: failed to create
			1: created
			2: not found 
			3: found
		*/
		
		function run(){
			$this->pkg = db()->package('Nicename');
			$this->run_ajax();	
		}
		
		protected $ajax_methods = array(
			'nameme',
			'findme'
		);	
		
		function respond($response){
			OB()->set_header('X-JSON', new json($response));
			OB()->flush();
			exit;
		}
		
		function typename($type){
			switch($type){
				case 'L': return 'Resource Link';
				case 'O': return 'Object';
				case 'B': return 'Blob';
				case 'E': return 'Evaluated Code';
				case 'J': return 'Javascript Object Notation';
				case 'Z': return 'Serialized Data';
				case 'S': return 'String';
				case 'I': return 'Integer';
				case 'N': return 'Number';
			}
		}
		
		function check_paths($nicename){
			list($name, $path, $nicename) = $this->pkg->read_nicename($nicename);
			$a = explode('.', $path);
			$names = array();
			for($i=0; $i<count($a); $i++) $names[] = (($i) ? $names[$i-1].'.' : '').$a[$i];
			foreach($names as $nicename){
				if(!$n = $this->pkg->get($nicename, false)) continue;
				$this->respond(array(
					'success'=>0,
					'code'=>3,
					'details'=>object(
						'message', 'found',
						'name', $nicename,
						'type', $n->type,
						'typename', $this->typename($n->type)
					)
				));
			}
		}
		
		function nameme($o){
			list($id, $nicename, $overwrite) = array($o->id, $o->name, $o->get('overwrite'));
			if(!$overwrite) $this->check_paths($nicename);
			if($n = $this->pkg->get($nicename, false)){
				if(!$overwrite){
					$name = ($n->path ? $n->path.'.' : '').$n->name;
					$this->respond(array(
						'success'=>0,
						'code'=>3,
						'details'=>object(
							'message', 'found',
							'name', $name,
							'type', $n->type,
							'typename', $this->typename($n->type)
						)
					));
				}
				$this->pkg->destroy($nicename);
			}
			$nicename = $this->pkg->new_name($nicename, 'L', $id);
			$success = intval((bool)$nicename);
			$this->respond(array(
				'success'=>$success,
				'code'=>$success,
				'details'=>object(
					'message', ($success ? 'created' : 'failed to create'),
					'name', $nicename 
				)
			));
		}
		
		function findme($o){
			$id = $o->id;
			$names = array();
			$data = $this->pkg->al()->select(array('path', 'name'), $this->pkg->table(), array('type'=>'L', 'value'=>$id));
			if($success = intval((bool)$data)) foreach($data as $name) $names[] = ($name['path'] ? $name['path'].'.' : '').$name['name'];
			$this->respond(array(
				'success'=>$success,
				'code'=>$success+2,
				'details'=>object(
					'message', ($success ? 'found' : 'not found'),
					'names', $names
				)
			));
		}
		
	}

?>